package com.gm.commonlib.network.basenetwork.numberformat;

import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;
import com.youth.banner.util.LogUtils;

import java.io.IOException;

/**
 * Created by Yuanye on 2017/4/12.
 */
public class OriginalIntegerDefault0Adapter extends TypeAdapter<OriginalInteger> {

    @Override
    public void write(JsonWriter out, OriginalInteger value) throws IOException {
        out.value(value);
    }

    @Override
    public OriginalInteger read(JsonReader in) throws IOException {
        if (in.peek() == JsonToken.NULL) {
            in.nextNull();
            return null;
        }


        String result = in.nextString();
        if(result.equals("") || result.equals("null")) {
            return null;
        }

        Integer resultInteger = null;
        try {
            resultInteger = Integer.parseInt(result);
        } catch (Exception e) {
            LogUtils.d(e.toString());
            try {
                resultInteger = (int)Double.parseDouble(result);
            } catch (Exception e1) {
                resultInteger = null;
            }
        }

        if(resultInteger != null) {
            return new OriginalInteger(resultInteger);
        }

        return null;
    }
}
